package com.tiantianfresh.view.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.tiantianfresh.model.web.AlipayConfig;
import com.tiantianfresh.view.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @Title  订单控制类
 *
 */
@Controller
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;
    /**
     *
     * @param orderNo  订单编号
     * @param subject  套餐名称
     * @param amount  价钱
     * @param body 套餐详情
     * @return
     * @throws AlipayApiException
     */
    @RequestMapping("/apply/pay")
    @ResponseBody
    public String pay(@RequestParam("orderNo")String orderNo,
                      @RequestParam("subject")String subject,
                      @RequestParam("amount")Double amount,
                      @RequestParam("body")String body) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://127.0.0.1:8080/reception/alipay/apply/success");//同步
      //alipayRequest.setNotifyUrl("http://127.0.0.1:9010/demo");//异步 99.9999999%
        System.out.println("异步");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderNo +"\","
                + "\"total_amount\":\""+ amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }

    /**
     * 支付完后成功跳转
     * @param out_trade_no 商品订单id
     * @param
     * @return
     */
    @RequestMapping("/apply/success")
    public String getJie(String out_trade_no,String method,String total_amount,String sign){
        /**
         * 把订单id改为1
         */
        //orderContrlloer.xiugaiOrder(out_trade_no);
        Map<String, Object> map = new HashMap<>();
        map.put("orderid",out_trade_no);
        alipayService.paymentComplete(map);
        return "redirect:http://127.0.0.1:8848/reception/shop-order.html";
    }

}
